package com.pan.note.controller;

import com.pan.note.service.LoginService;
import com.pan.note.util.JwtUtil;
import com.pan.note.vo.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录相关controller
 */
@Controller
@RequestMapping(value = "/note")
@Slf4j
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 登录方法
     * @param userLoginVo 传参
     * @return 登陆结果
     */
    @ResponseBody
    @RequestMapping("/user/login")
    public ResponseEntity<Map<String,String>> userLogin(@RequestBody UserLoginVo userLoginVo){
        Map<String,String> result = new HashMap<>();
        if (loginService.Login(userLoginVo)) {
            String userName = loginService.getUserName(userLoginVo.getAccountId());
            String token = JwtUtil.sign(userLoginVo.getAccountId(),userLoginVo.getUserPassword());
            result.put("userName",userName);
            result.put("userToken",token);
            result.put("userId", userLoginVo.getAccountId());
            log.info("accountId:{},userName:{}",userLoginVo.getAccountId(),userName);
            return ResponseEntity.ok(result);
        } else {
            log.info("登录失败");
            result.put("msg","登录失败,用户名或密码错误");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
        }
    }

    @ResponseBody
    @RequestMapping("/hello")
    public String sayHello(){
        return "请求成功";
    }
}
